from sqlalchemy.engine.result import null_result

from app.Pojo.BUser import BUser
from app.Mapper.UserMapper  import UserMapper
from app.Utils.exceptions import BusinessException
from datetime import datetime
import hashlib


class UserService:
    def __init__(self, db):
        self.mapper = UserMapper(db)

    def add_user(self, data):
        """新增用户"""
        # 检查用户名是否已存在
        username = data.get('username')
        if self.mapper.get_by_username(username):
            raise BusinessException(400, "用户名已存在")

        # 创建用户对象
        user = BUser(
            username=username,
            password=self._encrypt_password(data.get('password')),  # 密码加密
            role=data.get('role', '1'),
            status=data.get('status', '1'),
            nickname=data.get('nickname'),
            email=data.get('email'),
            mobile=data.get('mobile'),
            create_time=datetime.utcnow()
        )

        # 保存用户
        result = self.mapper.create_user(user)
        #
        # return {
        #     'id': result.id,
        #     'username': result.username,
        #     'nickname': result.nickname or username,
        #     'role': result.role,
        #     'status': result.status,
        #     'create_time': result.create_time.strftime('%Y-%m-%d %H:%M:%S')
        # }

    def delete_users(self, ids):
        """批量删除用户"""
        if not ids:
            raise BusinessException(400, "缺少必要参数: ids")

        # 检查用户是否存在
        for id in ids:
            if not self.mapper.get_by_id(id):
                raise BusinessException(404, f"用户ID {id} 不存在")

        self.mapper.delete_users(ids)

    def list_users(self, page, page_size):
        """分页查询用户"""
        users, total = self.mapper.list_users(page, page_size)

        return {
            'total': total,
            'page': page,
            'pageSize': page_size,
            'list': [
                {
                    'id': user.id,
                    'username': user.username,
                    'nickname': user.nickname or user.username,
                    'role': user.role,
                    'status': user.status,
                    'create_time': user.create_time.strftime('%Y-%m-%d %H:%M:%S')
                }
                for user in users
            ]
        }

    def update_user(self, data):
        """编辑用户"""
        id = data.get('id')
        user = self.mapper.get_by_id(id)
        if not user:
            raise BusinessException(404, "用户不存在")

        # 更新用户信息
        if 'nickname' in data:
            user.nickname = data['nickname']
        if 'role' in data:
            user.role = data['role']
        if 'status' in data:
            user.status = data['status']
        if 'email' in data:
            user.email = data['email']
        if 'mobile' in data:
            user.mobile = data['mobile']

        # 如果有密码更新，需要加密
        if 'password' in data:
            user.password = self._encrypt_password(data['password'])

        user.update_time = datetime.utcnow()

        # 保存更新
        result = self.mapper.update_user(user)

        # return {
        #     'id': result.id,
        #     'username': result.username,
        #     'nickname': result.nickname,
        #     'role': result.role,
        #     'status': result.status,
        #     'email': result.email,
        #     'mobile': result.mobile,
        #     'update_time': result.update_time.strftime('%Y-%m-%d %H:%M:%S')
        # }

    def get_user(self, id):
        """根据ID查询用户"""
        user = self.mapper.get_by_id(id)
        if not user:
            raise BusinessException(404, "用户不存在")

        return {
            'id': user.id,
            'username': user.username,
            'nickname': user.nickname or user.username,
            'role': user.role,
            'status': user.status,
            'email': user.email,
            'mobile': user.mobile,
            'create_time': user.create_time.strftime('%Y-%m-%d %H:%M:%S')
        }

    def search_users(self, username):
        """根据用户名搜索用户"""
        users = self.mapper.search_users(username)

        return [
            {
                'id': user.id,
                'username': user.username,
                'nickname': user.nickname or user.username,
                'role': user.role,
                'status': user.status,
                'create_time': user.create_time.strftime('%Y-%m-%d %H:%M:%S')
            }
            for user in users
        ]

    def delete_user(self, id):
        """根据ID删除用户"""
        user = self.mapper.get_by_id(id)
        if not user:
            raise BusinessException(404, "用户不存在")

        self.mapper.delete_user(id)

    def _encrypt_password(self, password):
        """密码加密处理"""
        if not password:
            return ""
        return hashlib.md5(password.encode('utf-8')).hexdigest()